<template>
  <view class="bx-table">
    <!--    <view class="table-name bg-white padding-sm text-blue" @click="showTable()" :class="{'text-bold':show}">
      <text>{{tableName||''}}</text>
      <text class="cuIcon-right icon" :class="{'to-bottom':show}"> </text>
    </view> -->
    <slot name="title"></slot>
    <view class="bx-table-content" :class="{show:show}">
      <uni-table border stripe emptyText="暂无更多数据" class="uni-table" v-if="tableHeaders&&tableHeaders.length>0">
        <!-- 表头行 -->
        <uni-tr>
          <uni-th align="center" v-for="header in tableHeaders">{{header.label}}</uni-th>
          <uni-th align="center" v-if="tableType==='list'&&rowButton&&rowButton.length>0">操作</uni-th>
        </uni-tr>
        <!-- 表格数据行 -->
        <uni-tr v-for="item in list">
          <uni-td align="center" v-for="header in tableHeaders">
            <text
              v-if="header.col_type==='Dict'&&dictOptions&&dictOptions[header.column]&&dictOptions[header.column][item[header.column]]">{{dictOptions[header.column][item[header.column]]}}</text>
            <text v-else-if="item[header.column]===0">0</text>
            <text v-else>{{item[header.column]||''}}</text>

          </uni-td>
          <uni-td align="center" v-if="tableType==='list'&&rowButton&&rowButton.length>0"><button
              class="cu-btn sm bg-blue margin-right-xs" v-show="showButton(item,btn)" v-for="btn in rowButton"
              @click="handleClick(item,btn)">{{btn.button_name||''}}</button></uni-td>
        </uni-tr>
      </uni-table>
    </view>
    <view class="bx-pagniation" v-show="show">
      <uni-pagination title="标题文字" show-icon="true" :pageSize="rownumber" :total="total" :current="pageNo"
        @change="changePage"></uni-pagination>
    </view>
    <!--  <view class="cu-modal bottom-modal" :class="{show:modalName==='updateForm'}">
      <view class="cu-dialog" @click="showModal()">
       
        
      </view>
    </view> -->
    <u-popup v-model="showUpdateForm" mode="bottom">
      <view class="" v-if="curFormV2">
        <bx-form ref="bxUpdateForm" :service="curFormV2.service_name" :pageType="'update'" :BxformType="'update'"
          :fields="curFormV2._fieldInfo" v-if="curFormV2&&curFormV2.service_name">
        </bx-form>
        <view class="button-box" v-if="curFormV2._formButtons">
          <button class="cu-btn bg-blue" v-for="btn in curFormV2._formButtons"
            v-show="['reset'].includes(btn.button_type)===false" @click="onButton(btn)">{{btn.button_name}}</button>
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script>
  export default {
    name: "bx-table",
    data() {
      return {
        total: 0,
        pageNo: 1,
        colV2: {},
        list: [],
        show: true,
        modalName: "",
        showUpdateForm: false,
        curFormV2: {},
        curRow: {}
      };
    },
    props: {
      // 表格顶部标题
      tableName: {
        type: String
      },
      appName: {
        type: String
      },
      serviceName: {
        type: String
      },
      rownumber: {
        type: Number,
        default: 5
      },
      use_type: {
        type: String,
        default: 'list'
      },
      condition: {
        type: Array,
      },
      tableType: {
        type: String,
        default: 'list'
      }
    },
    computed: {
      dictOptions() {
        if (Array.isArray(this.tableHeaders) && this.tableHeaders.length > 0) {
          let dictFields = this.tableHeaders.filter(item => item.col_type === 'Dict');
          if (dictFields.length > 0) {
            return dictFields.reduce((res, cur) => {
              if (Array.isArray(cur.options) && cur.options.length > 0) {
                res[cur.column] = cur.options.reduce((a, b) => {
                  a[b.value] = b.label;
                  return a
                }, {})
              }
              return res
            }, {})
          }
        }
      },
      rowButton() {
        if (Array.isArray(this.colV2?.rowButton)) {
          if (this.serviceName == 'srvmarket_pre_cost_calc_part_select') {
            return []
          }
          return this.colV2.rowButton.filter(item => {
            if (item.permission === false) {
              return false
            }
            if (item.button_type == 'detail') {
              return false
            }
            // if(item.disp_exps){

            // }
            return true
          })
        }
      },
      tableHeaders() {
        if (Array.isArray(this.colV2?._fieldInfo)) {
          if (this.colV2?.service_name === 'srvmarket_pre_dept_opinion_select' && this.tableType === 'list') {
            // 部门意见查询
            return this.colV2?._fieldInfo.filter(item => ["dept_no"].includes(item.column))
          } else {
            return this.colV2?._fieldInfo.filter(item => {
              return item?._colDatas?.in_list === 1
            })
          }
          return this.colV2?._fieldInfo
        }
      }
    },
    mounted() {
      if (this.serviceName) {
        this.getListV2()
        this.getList()
      }
    },
    methods: {
      getFieldModel() {
        return {
          type: "listUpdate",
          list: this.list.filter(item => item._is_update === true)
        }
      },
      onButton(btn) {
        if (btn?.button_type === 'edit') {
          let req = this.$refs.bxUpdateForm.getFieldModel();
          if (Object.keys(req).length > 0) {
            Object.keys(req).forEach(key => {
              this.list = this.list.map(item => {
                if (this.curRow?.id && this.curRow.id === item.id) {
                  item[key] = req[key]
                  item._is_update = true
                }
                return item
              })
            })
          }
          this.showUpdateForm = false
        }
      },
      handleClick(data, btn) {
        this.curRow = data
        let buttonInfo = this.deepClone(btn)
        let rowData = this.deepClone(data)
        if (buttonInfo.operate_params && typeof buttonInfo.operate_params === 'string') {
          // 序列化操作参数
          try {
            buttonInfo.operate_params = JSON.parse(buttonInfo.operate_params);
            if (Array.isArray(buttonInfo.operate_params?.condition) && buttonInfo.operate_params.condition
              .length > 0) {
              buttonInfo.operate_params.condition.forEach(cond => {
                if (typeof cond.value === 'object' && cond.value.value_type === 'rowData') {
                  cond.value = rowData[cond.value.value_key];
                } else if (typeof cond.value === 'object' && cond.value.value_type ===
                  'constant') {
                  cond.value = cond.value.value;
                }
              });
            }

            if (Array.isArray(buttonInfo.operate_params?.data) && buttonInfo.operate_params.data.length >
              0) {
              buttonInfo.operate_params.data.forEach(data => {
                if (typeof data === 'object') {
                  Object.keys(data).forEach(item => {
                    if (typeof data[item] === 'object' && data[item].value_type ===
                      'rowData') {
                      data[item] = rowData[data[item].value_key];
                    } else if (typeof data[item] === 'object' && data[item]
                      .value_type === 'constant') {
                      data[item] = data[item].value;
                    }
                  });
                }
              });
            }
          } catch (e) {
            //TODO handle the exception
          }
        }

        // this.getUpdateV2()
        if (btn?.button_type) {
          switch (btn.button_type) {
            case 'edit':
              this.getUpdateV2(rowData, buttonInfo).then(res => {
                if (res) {
                  this.curFormV2 = res
                  this.showUpdateForm = true
                  // this.showModal('updateForm')
                }
              })
              break;
          }
        }

      },
      showModal(name) {
        this.modalName = name
      },
      showButton(data, btn) {
        if (btn?.disp_exps) {
          if (!top?.user?.user_no) {
            top.user = uni.getStorageSync('login_user_info')
          }
          return eval(btn.disp_exps)
        }
        return true
      },
      showTable() {
        this.show = !this.show
      },
      async getDefaultVal(rowData, btn, serviceName, condition) {
        let app = btn.application || uni.getStorageSync('activeApp');

        let url = this.getServiceUrl(app, serviceName, 'select');
        let req = {
          serviceName: serviceName,
          colNames: ['*'],
          condition: condition,
          page: {
            pageNo: 1,
            rownumber: 10
          }
        };
        let res = await this.$http.post(url, req);
        if (res.data.state === 'SUCCESS') {
          if (Array.isArray(res.data.data) && res.data.data.length > 0) {
            return res.data.data[0];
          }
        }
      },
      async getUpdateV2(data, btn) {
        let app = btn.application || this.appName || uni.getStorageSync('activeApp');
        let self = this;
        let colVs = await this.getServiceV2(btn.operate_service, 'update', 'update', app);
        // colVs.srv_cols = colVs.srv_cols.filter(item => item.in_list === 1 || item.in_list === 2);
        let condition = [{
          colName: 'id',
          ruleType: 'eq',
          value: data.id
        }]
        let defaultVal = data

        colVs._fieldInfo = this.setFieldsDefaultVal(colVs._fieldInfo, defaultVal);

        console.log('colVs', colVs);
        return colVs;
      },
      async getListV2() {
        let app = this.appName || uni.getStorageSync('activeApp');
        let self = this;
        let colVs = await this.getServiceV2(this.serviceName, 'list', this.use_type, app);
        colVs.srv_cols = colVs.srv_cols.filter(item => item.in_list === 1 || item.in_list === 2);
        console.log('colVs', colVs);
        this.colV2 = colVs;
        return colVs;
      },
      refresh() {
        this.pageNo = 1;
        this.getList()
      },
      getList() {
        let app = this.appName || uni.getStorageSync('activeApp');
        let req = {
          "serviceName": this.serviceName,
          "colNames": ["*"],
          "condition": this.condition || [],
          "page": {
            "pageNo": this.pageNo || 1,
            "rownumber": this.rownumber
          }
        }
        let url = this.getServiceUrl(app, this.serviceName, 'select');
        this.$http.post(url, req).then(res => {
          if (res.data.state === 'SUCCESS') {
            this.list = res.data.data;
            this.total = res.data.page.total
          }
        })
      },
      changePage(e) {
        let {
          type,
          current
        } = e;
        if (type === 'prev') {
          this.pageNo--
        } else if (type === 'next') {
          this.pageNo++
        }
        this.getList()
      },
    },
  }
</script>

<style lang="scss" scoped>
  .table-name {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .icon {
      transition: transform .3s ease;

      &.to-bottom {
        transform: rotate(90deg);
      }
    }
  }

  .cu-modal {}

  .bx-table-content {
    display: block;
    overflow-x: auto;
    height: 0;
    transition-property: height, border-bottom-width;
    transition-duration: 0.3s;
    /* #ifndef APP-NVUE */
    will-change: height;

    /* #endif */
    &.show {
      height: auto;
    }
  }

  .bx-pagniation {
    padding: 10px 20px;
    display: flex;
    justify-content: center;
  }

  .button-box {
    text-align: center;
    padding: 20px;

    .cu-btn {
      margin-right: 10px;
    }
  }
</style>
